package cn.yx.common.security.webmvc.handler;

import cn.yx.common.core.enums.CharsetEnum;
import cn.yx.common.core.enums.ContentTypeEnum;
import cn.yx.common.core.enums.ResponseCodeEnum;
import cn.yx.common.core.pojo.ResponseVo;
import cn.yx.common.core.util.json.jackson.JsonUtil;
import cn.yx.common.security.pojo.JwtUserDetails;
import cn.yx.common.security.service.JwtTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>用户认证成功处理器.
 * 认证成功，需要为此用户生成一个token并返回给客户端</p>
 *
 * @author Wgssmart
 */
@Component
@Slf4j
public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private final JwtTokenService jwtTokenService;

    public CustomAuthenticationSuccessHandler(JwtTokenService jwtTokenService) {
        this.jwtTokenService = jwtTokenService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        JwtUserDetails jwtUserDetails = (JwtUserDetails) authentication.getPrincipal();
        log.info("authentication success, user id: {}, username: {}", jwtUserDetails.getId(), jwtUserDetails.getUsername());
        String token = jwtTokenService.generateToken(jwtUserDetails);
        response.setContentType(ContentTypeEnum.JSON.getValue());
        response.setCharacterEncoding(CharsetEnum.UTF8.getValue());
        response.getWriter().write(JsonUtil.toJsonStr(ResponseVo.ok(ResponseCodeEnum.OK.getMessage(), token)));
    }

}